/*
 * @Description:
 * @Author: Zzt
 * @Date: 2022-10-26 20:00:00
 * @LastEditTime: 2022-10-31 14:18:08
 */
import { createContext, useReducer, useEffect, useContext } from 'react';
import { message, Modal } from 'antd';
import {
  ADD_BOXLIST,
  DELETE_BOXLIST,
  EDIT_BOXLIST,
  SET_SELECT_KEY,
  GET_BOXLIST
} from '../constants';
import {
  addBoxNorms,
  fetchBoxNormsListByPage,
  editBoxNorms,
  delBoxNorms
} from '@/api/box/specifications';
import { BoxConfigReducer } from '../reducers/BoxConfigReducer';
const initialState = {
  boxListData: [],
  selectItems: []
};
const BoxConfigContext = createContext();
const BoxConfigContextProvider = (props) => {
  const [state, dispatch] = useReducer(BoxConfigReducer, initialState);
  const actions = {
    getBoxListData(data) {
      return new Promise((resolve, reject) => {
        fetchBoxNormsListByPage(data)
          .then((res) => {
            const { data } = res;
            dispatch({ type: GET_BOXLIST, data: data.results });
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    setSelectKey(data) {
      dispatch({ type: SET_SELECT_KEY, data });
    },
    /* 增加新盒配置项 */
    addBoxListData(data) {
      addBoxNorms(data).then((res) => {
        const { data } = res;
        console.log(data);
        dispatch({ type: ADD_BOXLIST, data });
      });
    },
    /* 删除盒配置项 */
    delBoxConfigFunc(id, title = '确认删除此盒规格？') {
      Modal.confirm({
        title: '删除',
        content: title,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          delBoxNorms(ids).then((res) => {
            message.success('删除成功');
            const data = res.data.map((item) => parseInt(item, 10));
            dispatch({ type: DELETE_BOXLIST, ids: data });
          });
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    },
    /* 编辑盒规则配置 */
    editBoxConfig(query) {
      return new Promise((resolve, reject) => {
        editBoxNorms(query)
          .then((res) => {
            const { data } = res;
            dispatch({ type: EDIT_BOXLIST, data, id: data.id });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    }
  };
  useEffect(() => {}, []);
  return (
    <BoxConfigContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </BoxConfigContext.Provider>
  );
};
export const useBoxConfigContext = () => {
  return useContext(BoxConfigContext);
};
export { BoxConfigContext, BoxConfigContextProvider };
